// pages/main/index.js
Page({
    data: {
        msg: '请扫码开门或定位门店',
        isLoading: true,
        urlAddress: getApp().globalData.imageUrl,
        isFirst: true,
        isShow: false,
        openid: '',
        userInfo: {},
        isHaveShopCode: false,
        isMustPosition: false

    },
    onLoad: function(options) {
        //判断是否扫码
        if (options.shopCode) {
            getApp().globalData.common.shopCode = options.shopCode;
            getApp().globalData.common.souce = options.souce;
            wx.setStorageSync('shopCode', options.shopCode);
            this.setData({
                isHaveShopCode: true
            })
        }
        //判断是否有店铺code缓存
        if (wx.getStorageSync('shopCode')) {
            this.setData({
                isMustPosition: true
            })
        }
        //判断是否有用户缓存
        if (wx.getStorageSync('openId')) {
            if (wx.getStorageSync('newUser')) {

            } else {
                this.setData({
                    isFirst: false
                });
                this.appletLogin();
            }
        } else {
            this.getUserId();
        }

    },
    onReady: function() {

    },
    onShow: function() {
        // 页面显示

    },
    onHide: function() {
        // 页面隐藏
    },

    onUnload: function() {
        // 页面关闭
    },
    //
    getUserId: function() {
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        var _self = this;
        wx.login({
            success: function(res) {
                wx.hideLoading();
                if (res.code) {
                    var code = res.code;
                    _self.acquireOpenId(code)
                } else {

                }
            },
            fail: function(res) {
                console.log(res)
            }
        });

    },
    //用code获取openId,是否是新用户,并缓存 
    acquireOpenId: function(code) {
        var _self = this;
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        wx.request({
            // url: getApp().globalData.baseUrl + '/appletOpenId.do',
            url: getApp().globalData.baseUrl + '/applet/autoLogin.do',
            data: {
                code: code
            },
            success: function(response) {
                wx.hideLoading();
                const res = response.data
                if (res.code == 200) {
                    if (res.obj.first) {
                        _self.setData({
                            isFirst: true,
                            openid: res.obj.openId
                        });
                        wx.setStorageSync('openId', res.obj.openId);
                        wx.setStorageSync('newUser', true);
                        _self.getUserInfo();
                    } else {
                        //老用户	
                        _self.setData({
                            isFirst: false,
                            openid: res.obj.openId
                        });
                        wx.setStorageSync('openId', res.obj.openId);
                        _self.appletLogin();
                    }
                    return
                } else {
                    _self.setData({
                        isFirst: false
                    });
                    _self.showMyToast(_self, res.des)
                }
            }
        })
    },
    //老用户根据openid登录
    appletLogin: function() {
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        var _self = this
        wx.request({
            url: getApp().globalData.baseUrl + '/applet/login.do',
            method: 'get',
            data: {
                openId: wx.getStorageSync('openId'),
            },
            success: function(res) {
                wx.hideLoading();
                if (res.data.code == 200) {
                    getApp().globalData.userInfo.nickName = res.data.obj.nickName;
                    getApp().globalData.userInfo.avatarUrl = res.data.obj.avatarUrl;
                    getApp().globalData.userInfo.gender = res.data.obj.gender;
                    getApp().globalData.userInfo.level = res.data.obj.level;
                    getApp().globalData.userInfo.isBind = res.data.obj.isBind;
                    getApp().globalData.header.Cookie = 'SESSION=' + res.data.obj.session;
                    if (_self.data.isHaveShopCode) {
                        wx.switchTab({
                            url: '../index/index'
                        })
                    } else {
                        if (_self.data.isMustPosition) {
                            _self.getShopCode();
                        }
                    }
                } else {
                    _self.loadingErr();
                    _self.setData({
                        isFirst: false
                    });
                    _self.showMyToast(_self, res.data.des, 5000)
                }
            }
        })
    },
    getShopCode: function() {
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        var _self = this;
        wx.getLocation({
            type: 'gcj02',
            success: function(res) {
                wx.hideLoading();
                var latitude = res.latitude
                var longitude = res.longitude
                var speed = res.speed
                var accuracy = res.accuracy
                wx.request({
                    url: getApp().globalData.baseUrl + '/shop/locate.do',
                    data: {
                        longitude: longitude,
                        latitudes: latitude
                    },
                    header: {
                        'content-type': 'application/json' // 默认值
                    },
                    success: function(res) {
                        var shopCode = wx.getStorageSync('shopCode')
                        if (res.data.shopCode != shopCode) {
                            // wx.showToast({
                            //     title: res.data.shopCode + '/' + shopCode,
                            //     image: '../../image/error.png',
                            //     duration: 1000
                            // })

                        } else {

                            _self.setData({
                                isHaveShopCode: true
                            });
                            getApp().globalData.common.shopCode = res.data.shopCode;
                            getApp().globalData.common.shopName = res.data.shopName;
                            wx.switchTab({
                                url: '../index/index'
                            })

                        }

                    }
                })
            },
            fail: function() {
                wx.hideLoading();
                console.log("失败")
            }
        })

    },

    //获取用户信息
    getUserInfo: function() {
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        var _self = this;
        wx.getUserInfo({
            success: function(res) {
                wx.hideLoading();
                var userInfo = res.userInfo
                _self.setData({
                    userInfo: userInfo
                });
                getApp().globalData.userInfo.nickName = userInfo.nickName;
                getApp().globalData.userInfo.avatarUrl = userInfo.avatarUrl;
                getApp().globalData.userInfo.gender = userInfo.gender;
                // wx.showToast({
                //     title: "获取用户昵称:" + userInfo.nickName,
                //     image: '../../image/error.png',
                //     duration: 1000
                // })
            },
            fail: function() {
                wx.hideLoading();
            }
        })
    },
    //获取用户手机号
    getPhoneNumber: function(e) {
        if (!e.detail.iv || !e.detail.encryptedData) {
            this.loadingErr();
        } else {
            this.decryption(wx.getStorageSync('openId'), e.detail.iv, e.detail.encryptedData);
        }

    },
    //手机号解密、注册
    decryption: function(id, iv, encryptedData) {
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        var _self = this;
        wx.request({
            url: getApp().globalData.baseUrl + '/applet/decryptMobile.do',
            method: 'post',
            data: {
                openId: id,
                iv: iv,
                encryptedData: encryptedData,
                platform: 6,
                shopCode: getApp().globalData.common.shopCode,
                userInfo: _self.data.userInfo,
            },
            success: function(res) {
                wx.hideLoading();
                if (res.data.code == 200) {
                    _self.setData({
                        isFirst: false
                    });
                    wx.setStorageSync('newUser', false);
                    getApp().globalData.userInfo.nickName = res.data.obj.nickName;
                    getApp().globalData.userInfo.avatarUrl = res.data.obj.avatarUrl;
                    getApp().globalData.userInfo.gender = res.data.obj.gender;
                    getApp().globalData.userInfo.level = res.data.obj.level;
                    getApp().globalData.userInfo.isBind = res.data.obj.isBind;
                    getApp().globalData.header.Cookie = 'SESSION=' + res.data.obj.session;
                    if (_self.data.isHaveShopCode) {
                        wx.switchTab({
                            url: '../index/index'
                        })
                    } else {

                    }
                    return

                } else if (res.data.code = 999) {
                    _self.showMyToast(_self, res.data.des, 5000)
                } else {
                    _self.loadingErr();

                }

            }
        })

    },
    showMyToast: function(self, my_toast_tip, time = 2000, template = 'my_toast') {
        self.setData({
            template: template, //my_toast
            my_toast_tip: my_toast_tip
        })
        setTimeout(() => {
            self.setData({
                template: '', //my_toast
                my_toast_tip: ''
            })
        }, time)
    },
    turnAction: function() {
        getApp().globalData.common.shopCode = null;
        wx.switchTab({
            url: '../index/index'
        })
    },
    scanAction: function() {
        var _self = this;
        wx.scanCode({
            success: (res) => {
                if (!res.path) {
                    wx.showToast({
                        title: '此码非小程序码',
                        image: '../../image/error.png',
                        duration: 1000
                    })
                } else {
                    var shopCode = "";
                    var type = "";
                    shopCode = res.path.split("?")[1];
                    type = shopCode.split("&")[1];
                    shopCode = shopCode.split("&")[0];
                    shopCode = shopCode.split("=")[1];
                    type = type.split("=")[1];
                    getApp().globalData.common.shopCode = shopCode;
                    getApp().globalData.common.souce = type;
                    wx.setStorageSync('shopCode', shopCode);
                    wx.switchTab({
                        url: '../index/index'
                    })
                }
            }
        })
    },
    loadingErr: function() {
        wx.navigateTo({
            url: '../login/login'
        })
    }
})